<template>
  <view class="section">
    <view class="section-header">
      <text class="section-title">热门推荐</text>
      <text class="section-more" @click="goToProductList">查看更多</text>
    </view>
    <view class="product-list">
      <view class="product-card" v-for="(item, idx) in displayProducts" :key="item.id || idx" @click="goToDetail(item.id)">
        <image :src="getProductImage(item)" class="product-img" mode="aspectFill" />
        <view class="product-info">
          <text class="product-title">{{ item.title }}</text>
          <view class="product-meta">
            <text class="product-price">¥{{ item.price }}</text>
            <text class="product-location">{{ item.location }}</text>
          </view>
          <view class="product-user">
            <image :src="getUserAvatar(item.userId)" class="user-avatar" />
            <text class="user-name">{{ item.userName || '匿名用户' }}</text>
            <text class="product-time">{{ formatTime(item.createdAt) }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { request } from '@/utils/request.js';
import { API_BASE_URL } from '@/utils/config.js';

export default {
  props: {
    hotProducts: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      apiProducts: []
    };
  },
  computed: {
    displayProducts() {
      // 优先使用API数据，如果没有则使用props传入的数据
      return this.apiProducts.length > 0 ? this.apiProducts.slice(0, 4) : this.hotProducts;
    }
  },
  mounted() {
    this.loadHotProducts();
  },
  methods: {
    async loadHotProducts() {
      try {
        const response = await request({
          url: '/api/product/list',
          method: 'GET',
          data: {
            page: 1,
            pageSize: 6,
            sortBy: 'hot' // 按热度排序
          },
          showLoading: false
        });
        
        console.log('API响应数据:', response);
        
        // 解析API响应格式 {code: 200, message: "...", data: {products: [...], pagination: {...}}}
        if (response && response.code === 200 && response.data && response.data.products) {
          this.apiProducts = response.data.products;
          console.log('设置商品数据:', this.apiProducts);
        } else if (response && response.success && response.data && response.data.products) {
          // 兼容旧格式
          this.apiProducts = response.data.products;
          console.log('设置商品数据(旧格式):', this.apiProducts);
        } else if (response && response.data && Array.isArray(response.data)) {
          // 如果直接返回数组
          this.apiProducts = response.data;
          console.log('设置商品数据(数组格式):', this.apiProducts);
        } else if (response && Array.isArray(response)) {
          // 如果响应本身就是数组
          this.apiProducts = response;
          console.log('设置商品数据(直接数组):', this.apiProducts);
        } else {
          console.log('未找到商品数据，响应格式:', response);
        }
      } catch (error) {
        console.log('加载热门商品失败，使用默认数据:', error);
        // 失败时使用props数据，不显示错误提示
      }
    },
    
    goToProductList() {
      uni.navigateTo({
        url: '/pages/product/list'
      });
    },
    
    goToDetail(productId) {
      if (productId) {
        uni.navigateTo({
          url: `/pages/productDetail/index?id=${productId}`
        });
      }
    },
    
    getProductImage(product) {
       // 优先使用API返回的firstImageUrl字段
       if (product.firstImageUrl) {
         const img = product.firstImageUrl;
         if (img.startsWith('http')) {
           return img;
         }
         if (img.startsWith('/uploads/')) {
           return API_BASE_URL + img;
         }
         return img;
       }
       // 兼容imageUrls数组格式
       if (product.imageUrls && product.imageUrls.length > 0) {
         const img = product.imageUrls[0];
         if (img.startsWith('http')) {
           return img;
         }
         if (img.startsWith('/uploads/')) {
           return API_BASE_URL + img;
         }
         return img;
       }
       // 兼容旧格式
       if (product.img) {
         return product.img;
       }
       // 默认图片
       return `https://picsum.photos/300/200?random=${product.id || Math.random()}`;
     },
    
    getUserAvatar(userId) {
      if (!userId) return 'https://picsum.photos/40/40?random=default';
      return `https://picsum.photos/40/40?random=${userId}`;
    },
    
    formatTime(timeStr) {
      if (!timeStr) return '';
      
      const time = new Date(timeStr);
      const now = new Date();
      const diff = now - time;
      
      const minutes = Math.floor(diff / (1000 * 60));
      const hours = Math.floor(diff / (1000 * 60 * 60));
      const days = Math.floor(diff / (1000 * 60 * 60 * 24));
      
      if (minutes < 60) {
        return `${minutes}分钟前`;
      } else if (hours < 24) {
        return `${hours}小时前`;
      } else if (days < 7) {
        return `${days}天前`;
      } else {
        return time.toLocaleDateString();
      }
    }
  }
};
</script>

<style scoped>
.section { background: #fff; margin-top: 12px; padding: 12px; border-radius: 8px; }
.section-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; }
.section-title { font-weight: bold; font-size: 16px; }
.section-more { color: #888; font-size: 12px; }
.product-list { display: flex; gap: 12px; }
.product-card { width: 48%; background: #fff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 10px rgba(0,0,0,0.05); }
.product-img { width: 100%; height: 100px; object-fit: cover; }
.product-info { padding: 6px; }
.product-title { font-size: 13px; color: #333; margin-bottom: 4px; }
.product-meta { display: flex; justify-content: space-between; font-size: 12px; color: #888; }
.product-price { color: #FF5E5E; font-weight: bold; }
.product-user { display: flex; align-items: center; margin-top: 4px; }
.user-avatar { width: 16px; height: 16px; border-radius: 50%; margin-right: 4px; }
.user-name { font-size: 12px; color: #888; margin-right: 8px; }
.product-time { font-size: 12px; color: #bbb; }
</style>
